package com.mandao.oneplat.boot.dao;

import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by sunson on 2017/3/29.
 */
public class OneMongoCollection {
    String name;
    Field idField;
    Map<String, Field> propMap;
    MongoCollection<Document> document;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Field getIdField() {
        return idField;
    }

    public void setIdField(Field idField) {
        this.idField = idField;
    }

    public Map<String, Field> getPropMap() {
        return propMap;
    }

    public void setPropMap(Map<String, Field> propMap) {
        this.propMap = propMap;
    }

    public MongoCollection<Document> getDocument() {
        return document;
    }

    public void setDocument(MongoCollection<Document> document) {
        this.document = document;
    }

    public Document toBsonDocument(Object entity) {
        final Document document = new Document();
        propMap.forEach((prop, field) -> {
            try {
                field.setAccessible(true);
                Object value = field.get(entity);
                field.setAccessible(false);
                if (value != null) {
                    document.put(prop, value);
                }
            } catch (IllegalAccessException e) {
            }
        });
        return document;
    }

    public <T> T toEntity(Document document, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            propMap.forEach((prop, field) -> {
                try {
                    field.setAccessible(true);
                    field.set(t, document.get(prop));
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                }
            });
            return t;
        } catch (Exception e) {
        }
        return null;
    }
}
